package com.tgy.crud.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.annotation.EnableRabbit;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.amqp.RabbitRetryTemplateCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.retry.support.RetryTemplate;

@Slf4j
@Configuration
@EnableRabbit
public class RabbitMqConfig {

    @Bean
    public Jackson2JsonMessageConverter jackson2JsonMessageConverter(){

        //  增加 json转换器，在消息队列传输过程中使用json字符串形式传递
        return new Jackson2JsonMessageConverter();
    }


    @Bean
    public RabbitRetryTemplateCustomizer rabbitRetryTemplateCustomizer(){

        return  new RabbitRetryTemplateCustomizer() {
            @Override
            public void customize(Target target, RetryTemplate retryTemplate) {


            }
        };
    }

    @Bean
    public ApplicationRunner rabbitMQInitApplicationRunner(){

        return new ApplicationRunner() {

            @Value("${rabbitmq.init:false}")
            private boolean initFlag;

            @Autowired
            private AmqpAdmin amqpAdmin;

            @Override
            public void run(ApplicationArguments args) throws Exception {


//                log.info("amqpAdmin {} flag {}",amqpAdmin, initFlag);

                if (!initFlag){

                    return;
                }

                amqpAdmin.declareExchange(new FanoutExchange("login"));
                amqpAdmin.declareQueue(new Queue("login.email",true));
                amqpAdmin.declareQueue(new Queue("login.message",true));
                amqpAdmin.declareBinding(new Binding("login.email",Binding.DestinationType.QUEUE,"login","login",null));
                amqpAdmin.declareBinding(new Binding("login.message",Binding.DestinationType.QUEUE,"login","login",null));
            }
        };
    }
}
